﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Commands.RegionTypes.Delete;

public class DeleteRegionTypesCommandsHandler : IRequestHandler<DeleteRegionTypesCommandsRequest>
{
    private readonly IMapper _mapper;
    private readonly IRegionTypeRepository _regionTypeRepository;

    public DeleteRegionTypesCommandsHandler(IMapper mapper, IRegionTypeRepository regionTypeRepository)
    {
        _mapper = mapper;
        _regionTypeRepository = regionTypeRepository;
    }

    public async Task Handle(DeleteRegionTypesCommandsRequest request, CancellationToken cancellationToken)
    {
        var regionType = await _regionTypeRepository.FirstOrDefaultWithRegionsAsync(x => x.Id == request.Id, cancellationToken);
        if (regionType == null) throw new NotFoundException($"Тип региона с id '{request.Id}' не существует");
        if (regionType.Regions.Any()) throw new BadRequestException($"Тип региона '{regionType.Id} задействован в регионах: '{string.Join("', '", regionType.Regions.Select(x => x.Id))}'");

        await _regionTypeRepository.DeleteAsync(regionType, cancellationToken);
    }
}